package ch.kerbtier.malurus.renderers;

import java.util.HashMap;
import java.util.Map;

import ch.kerbtier.malurus.Component;
import ch.kerbtier.malurus.Renderer;
import ch.kerbtier.malurus.RenderProvider;
import ch.kerbtier.malurus.RequestContext;

public class JavaRenderProvider implements RenderProvider {
	private Map<String, Renderer> renderers = new HashMap<String, Renderer>();

	protected void addRenderer(String component, String realisation, Class renderer) {
		renderers.put(component + (realisation == null ? "" : "->" + realisation), new JavaRenderer(renderer));
	}

	public Renderer getRenderer(String component, String realisation) {
		return renderers.get(component + (realisation == null ? "" : "->" + realisation));
	}

	public class JavaRenderer implements Renderer {
		private Class javaComponentRenderer;

		public JavaRenderer(Class javaComponentRenderer) {
			this.javaComponentRenderer = javaComponentRenderer;
		}

		public void render(Component component, RequestContext requestContext) {
			if (component.isVisible()) {
				try {
					JavaComponentRenderer renderer = (JavaComponentRenderer) javaComponentRenderer.newInstance();

					renderer.setContext(requestContext);
					renderer.setSubject(component);

					renderer.render();

				} catch (InstantiationException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		}
	}
}
